package com.zf.powerjob.worker.api_client;

import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import tech.powerjob.client.PowerJobClient;

import java.util.Arrays;
import java.util.List;
import java.util.Optional;
import java.util.stream.Collectors;

/**
 * powerjob客户端配置，以API的形式操作服务端的任务和工作流
 *
 * @author Zhou Feng
 */
@Configuration
class PowerJobClientConfig {

    /**
     * PowerJob Server 地址，多个值用逗号分隔
     */
    @Value("${powerjob.worker.server-address}")
    private String host;

    /**
     * 应用名
     */
    @Value("${powerjob.client.pj-worker.app-name}")
    private String pjWorkerAppName;

    /**
     * 密码
     */
    @Value("${powerjob.client.pj-worker.password}")
    private String pjWorkerPassword;

    /**
     * 创建一个客户端，使用 “pj-worker” 应用的名称和密码，这样此客户端就可以操作 “pj-worker” 应用下的任务和工作流。
     * 客户端的功能通过调用 PowerJob Server提供的OpenApi实现
     */
    @Bean("pjWorkerPowerJobClient")
    @ConditionalOnProperty(prefix = "powerjob.worker", name = "enabled", havingValue = "true", matchIfMissing = false)
    public PowerJobClient pjWorkerPowerJobClient() {
        // 分割 host
        List<String> addressList = Arrays.stream(StringUtils.split(Optional.ofNullable(host).orElse(""), ","))
                .map(StringUtils::trim)
                .collect(Collectors.toList());
        return new PowerJobClient(addressList, pjWorkerAppName, pjWorkerPassword);
    }

}
